package com.sky.service.common.impl;

import com.sky.exception.TradeOrderIsCompletedException;
import com.sky.exception.UploadToAliossException;
import com.sky.mapper.common.ShortUrlMapper;
import com.sky.mapper.courier.CourierMapper;
import com.sky.mapper.courier.CourierTradeOrderMapper;
import com.sky.pojo.Courier;
import com.sky.pojo.CourierTradeOrder;
import com.sky.pojo.ShortUrl;
import com.sky.result.Result;
import com.sky.service.common.CommonService;
import com.sky.utils.AliOssUtil;
import com.sky.utils.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private CourierTradeOrderMapper courierTradeOrderMapper;

    @Autowired
    private CourierMapper courierMapper;

    @Autowired
    private ShortUrlMapper shortUrlMapper;

    @Override
    public Result<String> upload(MultipartFile file) {

        //上传到阿里云oss
        String fileName = "";
        //文件文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //随机字符串拼接后缀
        fileName = UUID.randomUUID().toString().replaceAll("-","")+suffix;
        String uploadPath = null;
        try {
            uploadPath = aliOssUtil.upload(file.getBytes(), fileName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new UploadToAliossException("文件上传到aliyunOss异常");
        }

        return Result.success(uploadPath);
    }


    @Override
    public Result<String> loadRouteInfo(Long tradeNo, Long courierId) {

        //判断是否已经结束了
        CourierTradeOrder tradeOrder = courierTradeOrderMapper.selectByTradeNo(tradeNo);
        if(tradeOrder.getWaybillStatus()==CourierTradeOrder.TRADE_COMPLETE ||
           tradeOrder.getWaybillStatus()==CourierTradeOrder.CANCLE_TRADE){
            throw new TradeOrderIsCompletedException("订单已结束");
        }

        //1.用户地址
        String customerAddress = MapUtils.addressToLnglat(tradeOrder.getCustomerAddress());
        //2.商家地址
        String shopAddress = MapUtils.addressToLnglat(tradeOrder.getShopAddress());
        //3.骑手地址
        Courier courier = courierMapper.selectById(courierId);
        String curLocation = courier.getCurLocation();
        String sb = customerAddress+"_"+shopAddress+"_"+curLocation;

        return Result.success(sb);
    }

    @Override
    public ShortUrl getShortUrl(String code) {

        ShortUrl shortUrl = shortUrlMapper.selectByCode(code);
        return shortUrl;
    }
}
